package com.yuexunit.mobilenurse.module.Patients.ui.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.base.AppContext;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.BloodCollection.ui.Act_BloodCollection_Joyree;
import com.yuexunit.mobilenurse.module.Chemical.ui.Act_ChemicalSearch_Joyree;
import com.yuexunit.mobilenurse.module.Login.ui.Act_Login;
import com.yuexunit.mobilenurse.module.Patients.adapter.PatientClassListAdapter;
import com.yuexunit.mobilenurse.module.Patients.adapter.PatientListAdapter;
import com.yuexunit.mobilenurse.module.Patients.bean.PatientClassList_Patinfo;
import com.yuexunit.mobilenurse.module.Patients.bean.PatientList_Patinfo;
import com.yuexunit.mobilenurse.module.Patients.model.impl.PatientListModel;
import com.yuexunit.mobilenurse.module.Patients.presenter.IPatientListPresenter;
import com.yuexunit.mobilenurse.module.Patients.presenter.impl.PatientListPresenter;
import com.yuexunit.mobilenurse.module.Patients.ui.Act_Main_Joyree;
import com.yuexunit.mobilenurse.module.Patients.ui.view.IPatientListView;
import com.yuexunit.mobilenurse.module.SignInput.bean.All_Sqlite_SignInputBean;
import com.yuexunit.mobilenurse.module.SignInput.bean.SignsInput_Data;
import com.yuexunit.mobilenurse.module.TxtNode.ui.Act_TxtRead;
import com.yuexunit.mobilenurse.widget.EmptyLayout;
import com.yuexunit.mobilenurse.widget.FooterLoadingLayout;
import com.yuexunit.mobilenurse.widget.PullToRefreshBase;
import com.yuexunit.mobilenurse.widget.PullToRefreshList;

import org.kymjs.kjframe.KJDB;
import org.kymjs.kjframe.ui.KJFragment;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by work-jx on 2017/6/14.
 */
public class Frag_PatientList_Joyree extends KJFragment implements IPatientListView {
    @Bind(R.id.empty_layout)
    public EmptyLayout mEmptyLayout;
    @Bind(R.id.patient_list)
    public PullToRefreshList mRefreshLayout;
    @Bind(R.id.nurse_id)
    public TextView nurse_id;
    @Bind(R.id.nurse_name)
    public TextView nurse_name;
    @Bind(R.id.nurse_lesion)
    public TextView nurse_lesion;
    @Bind(R.id.onekey_upload)
    public Button onekey_upload;
    @Bind(R.id.classify_tv)
    public TextView classify_tv;
    @Bind(R.id.classify_img)
    public ImageView classify_img;
    @Bind(R.id.patient_top)
    public LinearLayout patient_top;
    @Bind(R.id.check_collection)
    CheckBox checkCollection;

    /**
     * 加载病人列表状态
     */
    public static final int DOWNLOAD_SUCCESS = 1;
    public static final int DOWNLOAD_NODATA = 0;
    public static final int DOWNLOAD_NETERROR = -1;

    private ListView mList;
    private Act_Main_Joyree aty;
    //private Act_Main_Moto aty;
    private PatientListAdapter adapter;

    //病区号及病区名称
    private String Wardno, WardName;
    //护士相关信息
    private String NurseName, NurseId;

    //记录Log
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    //KJDB访问数据库
    KJDB kjdb;

    IPatientListPresenter presenter;

    ArrayList<PatientList_Patinfo> patientlist = new ArrayList<PatientList_Patinfo>();

    ArrayList<PatientClassList_Patinfo> patientClassList_patinfos = new ArrayList<PatientClassList_Patinfo>();
    private PatientClassListAdapter adapter_class;
    private List<Map<String, String>> menuData;
    private PopupWindow popMenu;
    private SimpleAdapter menuAdapter;
    private ListView popListView;
    private String classify = "全部";

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        aty = (Act_Main_Joyree) getActivity();
        View layout;
        layout = View.inflate(aty, R.layout.frag_patientlist, null);
        ButterKnife.bind(this, layout);
        return layout;
    }

    @Override
    protected void initData() {
        super.initData();
        kjdb = KJDB.create();
        NurseId = PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGID);
        NurseName = PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGNAME);
        WardName = PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_WARDNO_NAME);
        Wardno = PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_WARDNO_ID);
        listViewPreference();
        initPopMenu();
        presenter = new PatientListPresenter(new PatientListModel(), this);

        checkCollection.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked)
                {
                    PreferenceHelper.write(aty, AppConfig.MOBILE_INFO, AppConfig.COLLECTION_ISCHECK, false);
                }
                else {
                    PreferenceHelper.write(aty, AppConfig.MOBILE_INFO, AppConfig.COLLECTION_ISCHECK, true);
                }
            }
        });

        if(PreferenceHelper.readBoolean(aty, AppConfig.MOBILE_INFO, AppConfig.COLLECTION_ISCHECK))
        {
            checkCollection.setChecked(false);
        }
        else {
            checkCollection.setChecked(true);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (((ArrayList<All_Sqlite_SignInputBean>) kjdb.findAll(All_Sqlite_SignInputBean.class)).size() == 0) {
            onekey_upload.setText("没有体征数据");
            onekey_upload.setEnabled(false);
        } else {
            onekey_upload.setText("一键上传");
            onekey_upload.setEnabled(true);
        }
    }

    @Override
    protected void initWidget(View parentView) {
        super.initWidget(parentView);
        showNurseInfo(NurseId, NurseName, WardName);
        presenter.showPatientList(Wardno);
        presenter.getBaseTypes(Wardno);
        presenter.getAllTypes();
    }

    /**
     * 初始化ListView样式
     */
    private void listViewPreference() {
        mList = mRefreshLayout.getRefreshView();
        mList.setDivider(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
        mList.setOverscrollFooter(null);
        mList.setOverscrollHeader(null);
        mList.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        mRefreshLayout.setPullLoadEnabled(false);//设置上拉刷新功能关闭
        ((FooterLoadingLayout) mRefreshLayout.getFooterLoadingLayout())
                .setNoMoreDataText("已经是最新状态");

        mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
            }
        });

        mRefreshLayout.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                AppConfig.ISOVER_PATIENT = false;
                changeClass();
            }

            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                mRefreshLayout.setHasMoreData(false);
            }
        });

        mEmptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                changeClass();
            }
        });
    }

    private void dialog_exit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(aty);  //先得到构造器
        builder.setTitle("提示"); //设置标题
        builder.setMessage("是否确认退出?"); //设置内容
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { //设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); //关闭dialog
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.setClass(aty, Act_Login.class);
                aty.startActivity(intent);
                aty.finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }


    public void showNurseInfo(String NurseId, String NurseName, String WardNo) {
        nurse_id.setText(NurseId);
        nurse_name.setText(NurseName);
        nurse_lesion.setText(WardNo);
    }

    @Override
    public void oneKeyUpload(String bean, String info, All_Sqlite_SignInputBean signInputBean) {
        if ("0".equals(bean)) {
            kjdb.delete(signInputBean);
            ViewInject.toast("上传体征信息成功");
        } else {
            kjdb.delete(signInputBean);
            ViewInject.toast("当前时间点体征信息已录入");
        }

    }

    @Override
    public void showPatientList(ArrayList<PatientList_Patinfo> list) {
        AppConfig.ISOVER_PATIENT = true;
        patientlist = list;
        adapter = new PatientListAdapter(mList, patientlist, R.layout.item_patientlist);
        mList.setAdapter(adapter);
        mEmptyLayout.dismiss();
    }

    @Override
    public void showPatientClassList(ArrayList<PatientClassList_Patinfo> list) {
        AppConfig.ISOVER_PATIENT = true;
        patientClassList_patinfos = list;
        adapter_class = new PatientClassListAdapter(mList, patientClassList_patinfos, R.layout.item_patientlist);
        mList.setAdapter(adapter_class);
        mEmptyLayout.dismiss();
    }

    @Override
    public void PullDownRefreshState(int state) {
        switch (state) {
            case DOWNLOAD_SUCCESS:
                mRefreshLayout.onPullDownRefreshComplete();
                mRefreshLayout.onPullUpRefreshComplete();
                break;
            case DOWNLOAD_NETERROR:
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                break;
            case DOWNLOAD_NODATA:
                mEmptyLayout.setErrorType(EmptyLayout.NODATA);
        }
    }

    @Override
    public void saveBaseTypes(ArrayList<SignsInput_Data> baseList) {
        ((AppContext) getActivity().getApplication()).setBaseTypes(baseList);
    }

    @Override
    public void saveAllTypes(ArrayList<SignsInput_Data> allList) {
        ((AppContext) getActivity().getApplication()).setAllTypes(allList);
    }

    public boolean JudgeVisitNo(final String visitno) {
        for (int i = 0; i < patientlist.size(); i++) {
            if (visitno.equals(patientlist.get(i).getVisit_no())) {
                return true;
            }
        }
        return false;
    }

    @OnClick({R.id.out_login, R.id.panic_btn, R.id.chemical_btn, R.id.onekey_upload, R.id.txt_btn, R.id.classify_ll,
            R.id.blood_send_btn})
    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.out_login:
                dialog_exit();
                break;
            case R.id.panic_btn:
                ViewInject.toast("正在研发中");
//                intent.setClass(aty, Act_PanicInfo.class);
//                aty.startActivity(intent);
                break;
            case R.id.chemical_btn:
//                ViewInject.toast("正在研发中");
                intent.setClass(aty, Act_ChemicalSearch_Joyree.class);
                aty.startActivity(intent);
                break;
            case R.id.onekey_upload:
                presenter.oneKeyUpload((ArrayList<All_Sqlite_SignInputBean>) kjdb.findAll(All_Sqlite_SignInputBean.class));
                break;
            case R.id.txt_btn:
                intent.setClass(aty, Act_TxtRead.class);
                aty.startActivity(intent);
                break;
            case R.id.classify_ll:
                popListView.setAdapter(menuAdapter);
                popMenu.showAsDropDown(patient_top, 0, 2);
                classify_img.setBackgroundResource(R.drawable.spinner_up);
                break;
            case R.id.blood_send_btn:
                intent.setClass(aty, Act_BloodCollection_Joyree.class);
                aty.startActivity(intent);
                break;
        }
    }

    private void initPopMenu() {
        initMenuData();
        View contentView = View.inflate(aty, R.layout.popwin_supplier_list,
                null);
        popMenu = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        popMenu.setOutsideTouchable(true);
        popMenu.setBackgroundDrawable(new BitmapDrawable());
        popMenu.setFocusable(true);
        popMenu.setAnimationStyle(R.style.popwin_anim_style);
        popMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            public void onDismiss() {
                classify_img.setBackgroundResource(R.drawable.spinner_down);
            }
        });

        popListView = (ListView) contentView
                .findViewById(R.id.popwin_supplier_list_lv);
        contentView.findViewById(R.id.popwin_supplier_list_bottom)
                .setOnClickListener(new View.OnClickListener() {
                    public void onClick(View arg0) {
                        popMenu.dismiss();
                    }
                });
        menuAdapter = new SimpleAdapter(aty, menuData,
                R.layout.item_listview_popwin, new String[]{"name"},
                new int[]{R.id.listview_popwind_tv});

        popListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
                                    long arg3) {
                popMenu.dismiss();
                classify_img.setBackgroundResource(R.drawable.spinner_down);
                classify_tv.setText(menuData.get(pos).get("name"));
                classify = menuData.get(pos).get("name");
                changeClass();
            }
        });
    }

    private void initMenuData() {
        menuData = new ArrayList<Map<String, String>>();
        String[] menuStr1 = new String[]{"全部", "特级", "一级", "二级", "三级", "注射",
                "口服", "抽血"};
        Map<String, String> map1;
        for (int i = 0, len = menuStr1.length; i < len; ++i) {
            map1 = new HashMap<String, String>();
            map1.put("name", menuStr1[i]);
            menuData.add(map1);
        }
    }

    private void changeClass() {
        switch (classify) {
            case "全部":
                presenter.showPatientList(Wardno);
                break;
            case "特级":
                presenter.showPatientClassifyList(Wardno, "0", "-1", "-1", "-1");
                break;
            case "一级":
                presenter.showPatientClassifyList(Wardno, "1", "-1", "-1", "-1");
                break;
            case "二级":
                presenter.showPatientClassifyList(Wardno, "2", "-1", "-1", "-1");
                break;
            case "三级":
                presenter.showPatientClassifyList(Wardno, "3", "-1", "-1", "-1");
                break;
            case "注射":
                presenter.showPatientClassifyList(Wardno, "-1", "-1", "1", "-1");
                break;
            case "口服":
                presenter.showPatientClassifyList(Wardno, "-1", "1", "-1", "-1");
                break;
            case "抽血":
                presenter.showPatientClassifyList(Wardno, "-1", "-1", "-1", "1");
                break;
        }
    }

}
